/****************************************************/
/* server.cpp                                       */
/****************************************************/

#include "server.h"
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std ;

void wait(unsigned int seconds)
{
  clock_t goal = seconds * CLOCKS_PER_SEC + clock();
  while (clock() < goal);
}

server::server( string screen, string path, string m ) {

  screen_name = screen ;
  minecraft_path = path ;
  memory = m ;

}

void server::start() {

  string cmd = "cd "+ minecraft_path  +";screen -dmS " + screen_name + " java -Xincgc -Xmx"+ memory +" -jar " + minecraft_path +"minecraft_server.jar" ;

  cout << "Starting minecraft server..." ;
  if( system( cmd.c_str() ) != 0)
    cout << "Failed to start the server. Is the path right?" << endl ;
  
  cout << "done." << endl ;

}

void server::stop() {

  string cmd = "screen -S "+ screen_name + " -p 0 -X stuff `" + "printf \"stop\"\r`" ;

  cout << "Stopping minecraft server..." ;
  if( system( cmd.c_str() ) != 0 )
     cout << "Failed to stop server. Is it running?" << endl ;

  cout << "done." << endl ;
}

void server::restart() {
 
  stop();
  wait(3);
  start();

}

void server::backup() {

  string cmd ;
  
  cout << "Backing up server..." << endl ; ;
  
  //Disable saving
  cmd = "screen -S "+ screen_name + " -p 0 -X stuff `" + "printf \"save-off\"\r`" ;
  
  if( system( cmd.c_str() ) != 0 ) {
    
    cout << "Failed to disable saving. Stopping." << endl ;
    return ;

  }
  //Check if backup folder exists
  
  cmd = "cd " + minecraft_path + "backups" ; 

  if( system(cmd.c_str()) != 0 ) {
   
    cmd = "mkdir " + minecraft_path + "backups" ;
    
    if( system(cmd.c_str()) != 0 ) { 
      cout << "Failed to make backups folder" << endl; 
      return ;
    }
  }

  //Compress world and move it in to the backups folder with timestamp

  cmd = "cd " + minecraft_path + "; tar -czf " + minecraft_path + "backups/`date +%Y-%m-%d-%T`.tar.gz world" ;

  if( system(cmd.c_str()) != 0 ) {

    cout << "Failed to compress world. Stopping." << endl ; ;
    return ;

  }

  //Enable world saving
  
   cmd = "screen -S "+ screen_name + " -p 0 -X stuff `" + "printf \"save-on\"\r\
`" ;

   if( system( cmd.c_str() ) != 0 ) {

     cout << "Failed to enable saving. Stopping." << endl ;
     return ;

   }

   cout << "Backup done" << endl ;

}
